package xyz.heyaoshare.config.satoken.handler;

import cn.dev33.satoken.stp.StpInterface;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import xyz.heyaoshare.core.entity.system.User;
import xyz.heyaoshare.core.enums.system.user.SuperAdminEnum;
import xyz.heyaoshare.core.mapper.system.UserMapper;
import xyz.heyaoshare.utils.ObjectUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static xyz.heyaoshare.exceptions.code.ErrorInfo.USER_NOT_EXIST;
import static xyz.heyaoshare.exceptions.customize.ServerException.exception;

/**
 * 自定义权限加载处理器
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 上午11:55
 */
@Slf4j
@Component
public class PermissionsHandler implements StpInterface {

    @Resource
    private UserMapper userMapper;


    /**
     * 获取用户权限列表
     *
     * @param loginId 登录ID
     * @param loginType 登录类型
     * @return 用户权限列表
     * @throws xyz.heyaoshare.exceptions.customize.ServerException 当用户不存在时抛出异常
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Set<String> list = new HashSet<>();
        Long userId = (Long) loginId;

        if (ObjectUtils.isNotNull(loginId)) {
            User user = userMapper.selectOneById(userId);
            if (user == null) throw exception(USER_NOT_EXIST);

            if (user.getIsAdmin() == SuperAdminEnum.YES.getValue()) {
                Set<String> permissions = userMapper.selectPermissionsAll();
                for (String permission : permissions) {
                    String[] split = permission.split(",");
                    Collections.addAll(list, split);
                }
            } else {
                Set<String> permissions = userMapper.selectPermissions(userId);
                for (String permission : permissions) {
                    String[] split = permission.split(",");
                    Collections.addAll(list, split);
                }
            }
        }

        return list.stream().toList();
    }

    /**
     * 根据登录ID和登录类型获取角色列表
     *
     * @param loginId 登录ID
     * @param loginType 登录类型
     * @return 角色列表
     * @throws xyz.heyaoshare.exceptions.customize.ServerException 当用户不存在时抛出异常
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Set<String> list = new HashSet<>();
        Long userId = (Long) loginId;

        if (ObjectUtils.isNotNull(loginId)) {
            User user = userMapper.selectOneById(userId);
            if (user == null) throw exception(USER_NOT_EXIST);

            List<String> roles;
            if (user.getIsAdmin() == SuperAdminEnum.YES.getValue()) {
                roles = userMapper.selectRolesAll();
            } else {
                roles = userMapper.selectRoles(userId);
            }
            list.addAll(roles);
        }

        return list.stream().toList();
    }

}